<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Repository\ProductRepository;
use Dingo\Api\Exception\StoreResourceFailedException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Class ProductController
 * @package App\Http\Controllers\Api\V1
 */
class ProductController extends Controller
{
    /**
     * @var ProductRepository
     */
    public $product;

    /**
     * ProductController constructor.
     * @param $product
     */
    public function __construct(ProductRepository $product)
    {
        $this->product = $product;
    }

    /**
     * 获取最新商品数据  默认15条
     * @return $this
     */
    public function recent()
    {
        $rules = ['count' => 'integer|min:0|numeric|between:1,15'];
        $count = app('request')->only('count');
        if (!$count['count']){
            $count = ['count' => 15];
        }
        $validator = app('validator')->make($count, $rules);
        if ($validator->fails()){
            throw new StoreResourceFailedException('传入的条数必须在1-15的正整数', $validator->errors());
        }

        return  $this->product->getMostRecent($count['count']);
    }

    /**
     * 获取分类下的商品
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getAllInCategory()
    {
        $id = app('request')->only('id');
        $rule = ['id' => ['required', 'min:0', 'numeric', 'integer']];
        $validator = app('validator')->make($id, $rule);

        if ($validator->fails()){
            throw new StoreResourceFailedException('ID必须是正整数', $validator->errors());
        }
        return $this->product->getProductsByCategory($id['id']);
    }

    /**
     * 获取商品的详细参数
     * @param $id
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null|static|static[]
     */
    public function getOne($id)
    {
        $rules = ['id' => ['required', 'min:0', 'numeric', 'integer']];
        $validator = app('validator')->make(['id' => $id], $rules);
        if ($validator->fails()){
            throw new StoreResourceFailedException('ID必须是正整数', $validator->errors());
        }

        $product = $this->product->getProductDetail($id);
        if (!$product){
            throw new NotFoundHttpException('指定商品不存在，请检查参数', null, 20000);
        }
        return $product;
    }
}
